from django.shortcuts import render
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from . import models,ser
from .paginations import PageNumberPagination
from rest_framework.filters import OrderingFilter,SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from .filters import MyFilter,CourseFilterSet
# Create your views here.

#分类
class CourseCategoryView(GenericViewSet, ListModelMixin):
    queryset = models.CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = ser.CourseCategorySerializer

#课程类
class CourseView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class =ser.CourseSerializer
    pagination_class = PageNumberPagination

    #过滤和排序
    # filter_backends = [DjangoFilterBackend,OrderingFilter,MyFilter]
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filter_fields = ['course_category', 'students']
    ordering_fields = ['id', 'price']

    # #区间过滤
    # filter_backends = [DjangoFilterBackend,OrderingFilter]
    # ordering_fields = ['id', 'price', 'students']
    #
    # #配置类(自己写的类)
    # filter_class = CourseFilterSet

#排序与过滤
'''
排序：
按id正序倒序排序，按price 正序倒序排列
使用：http://127.0.0.1：8000/course/free/?ordering=-id
配置类：
    filter_backends=[OrderingFilter]
配置字段：
    ordering_fields=['id','price']

内置过滤：不能使用外键字段过滤
使用：http://127.0.0.1:8000/course/free/?search=39
按照price过滤(表自有的字段直接过滤)
配置类：
    filter_backends=[SearchFilter]
配置字段：
    search_fields=['price']
    
第三方：django-filter
安装：pip install django-filter
支持自有的字段的过滤的同时还支持外键字段的过滤
http://127.0.0.1:8000/course/free/?course_category=1
配置类：
    filter_backends=['DjangoFilterBackend']
配置字段：
    filtter_fields=['course_category]

django-filters指定某个字段过滤有两种方式
第一种：不支持区间过滤
    配置字段：
    filter_fields = ['course_category']
第二种：支持区间过滤
    配置字段==>配置类：
    class CourseFilterSet(FilterSet):
    min_price=
    max_price=
        class Meta:
            model = models.Course
            fields = ['course_category']
#使用：http://127.0.0.1:8001/course/free/?min_price=10&max_price=90   
'''





#课程章节接口
class CourseChapterView(GenericViewSet, ListModelMixin):
    queryset = models.CourseChapter.objects.filter(is_delete=False, is_show=True)
    serializer_class = ser.CourseChapterSerializer
    #不可能把所有的章节都展示出来，所以应该按照课程来展示对应的章节
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']


#课程名模糊搜索
class CourseSearchView(GenericViewSet, ListModelMixin):
    queryset = models.Course.objects.filter(is_delete=False, is_show=True)
    serializer_class = ser.CourseSerializer
    pagination_class = PageNumberPagination
    filter_backends = [SearchFilter]
    search_fields = ['name']